﻿
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using FPC.Offer.Common;
using System.IO;
using System;
using NLog;
using System.Web.SessionState;
namespace FPC.Offer.UI.GeneralProcessor.MangerEmp
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler, IReadOnlySessionState
    {

        FPC.Offer.Service.Police_FuzzTableService s = new Service.Police_FuzzTableService();
        FPC.Offer.Service.System_DeptTableService ss = new Service.System_DeptTableService();
        FPC.Offer.Service.System_RoleTableService role = new Service.System_RoleTableService();
        FPC.Offer.Service.Police_OrganizeTalbeService Org = new Service.Police_OrganizeTalbeService();
        private static Logger logger = LogManager.GetCurrentClassLogger();
        
        private const string UPLOAD_FOLDER = "~/File/";
        public void ProcessRequest(HttpContext context)
        {

            context.Response.ContentType = "text/plain";
            var UserName = context.Session[FPC.Offer.Common.SystemKeys.COOKIE_USER_NAME_REMEMBER];
            var AmilyID = Convert.ToInt32(context.Session[FPC.Offer.Common.SystemKeys.COOKIE_USER_UserID_REMEMBER]);
            var Actioon = context.Request["Actioon"].ToString();
            var userid = 0;
            var name = "";
            if (Actioon == EnumAction.Select.ToString())
            {               
                if (context.Request["name"] != "" && context.Request["name"] != null)
                {
                    name = context.Request["name"].ToString();
                }

                if (Convert.ToInt32(context.Request["id"]) != 0)
                {
                    userid = (Convert.ToInt32(context.Request["id"]));
                }

                var list = (from n in s.Select()
                            join m in ss.Select()
                                on n.DeptId equals m.DeptId
                            select new
                            {
                                DeptId = n.DeptId,
                                RoleId = n.RoleId,
                                LoginName=n.LoginName,
                                LoginPwd=n.LoginPwd,
                                UserCard=n.UserIDCard,              
                                UserId = n.AlarmId,
                                UserName = n.UserName,
                                UserSex = n.UserSex,
                                UserTel = n.UserTel,
                                UserEmail = n.UserEmail,
                                UserAddress = n.UserAddress,
                                UserPhoto = n.UserPhoto,
                                PoliticalStatus = n.FuzzUserStates,
                                OrganizeName = m.OreganizeSublevelId
                            }).ToList();
               if ((name != "" && name != null) || userid != 0)
                    {
                        if (name != "" || name != null && userid == 0)
                        {
                            if (name == "下拉")
                            {
                                DeptAndRole lst = new DeptAndRole();
                                lst.lst1 = ss.Select();
                                lst.lst2 = role.Select();
                                lst.lst3 = Org.Select();
                                lst.list4 = s.Find(x => x.RoleId == 2).ToList();
                                context.Response.Write(JsonConvert.SerializeObject(lst));
                            }
                            else {
                                //var m = s.Find(p => p.UserName.Contains(name)).ToList();
                                list = list.Where(p => p.UserName.Contains(name)).ToList();
                                context.Response.Write(JsonConvert.SerializeObject(list));
                            }

                        }

                        if (userid != 0&&(name == "" ||name == null))
                        {
                            //var m = s.Find(p => p.UserId == userid).ToList();
                            var emp=list.Where(x=>(x.UserId==userid)).FirstOrDefault();
                            string cc = "";
                                cc = "操作人警号:" + AmilyID.ToString();
                                cc += ",操作人：" + UserName.ToString() + "查看账户信息";
                                logger.Info(cc);
                            context.Response.Write(JsonConvert.SerializeObject(emp));
                        }
                    }
                    else
                    {
                        string cc = "";
                       
                            cc = "操作人警号:" + AmilyID.ToString();
                            cc += ",操作人：" + UserName.ToString() + "查看账户信息";
                            logger.Info(cc);
                        context.Response.Write(JsonConvert.SerializeObject(list));
                    }

                }
                //添加
                if (Actioon == EnumAction.Add.ToString())
                {
                    
                    var FileName="";
                    //接收上传过来的文件
                    if (context.Request["file"]!="")
                    {  
                        HttpPostedFile file = context.Request.Files[0];
                      //获得文件名
                        if (file.ContentLength > 0)
                        {
                            FileName = Path.GetFileName(file.FileName);
                        }
                        //string path = context.Request["getfiles"];//图片原始路径

                        //图片保存路径
                        string strPath = context.Request.MapPath("/Files/") ;
                        //判断是否存在路径，若无则创建该路径
                        if (!Directory.Exists(strPath))
                        {
                            Directory.CreateDirectory(strPath);
                        }
                         
                        file.SaveAs(strPath + FileName);
                    }

                    Model.Police_FuzzTable emp = new Model.Police_FuzzTable();
                    emp.UserName = context.Request["getname"].ToString();
                    emp.UserSex = context.Request["Getsex"].ToString(); ;
                    emp.UserTel = context.Request["gettel"].ToString();
                    emp.UserEmail = context.Request["getemail"].ToString();
                    emp.UserAddress = context.Request["getcity"].ToString();
                    emp.UserPhoto = "/Files/" + FileName;
                    emp.LoginName = context.Request["getloginname"].ToString();
                    emp.LoginPwd = Md5.Encrypt(context.Request["getloginpwd"].ToString());
                    emp.UserIDCard = context.Request["getidcard"].ToString(); 
                    emp.RoleId = Convert.ToInt32(context.Request["getrole"]);
                    emp.OrganizeId = Convert.ToInt32(context.Request["getOrganize"]);
                    emp.DeptId = Convert.ToInt32(context.Request["getdept"]);
                    emp.FuzzUserStates = 1;
                    emp.FuzzDate = DateTime.Now.ToLocalTime();


                    var i=s.Add(emp);
                    string cc = "";
                        cc = "操作人警号:" + AmilyID.ToString();
                        cc += ",操作人：" + UserName.ToString() + "添加账户信息";
                    logger.Info(cc);
                    context.Response.Write(i);
                }
                //修改
                if (Actioon == EnumAction.Update.ToString())
                {
                    int id = Convert.ToInt32(context.Request["getid"]);
                    var FileName = "";
                    //接收上传过来的文件
                    if (context.Request["files"] != "")
                    {
                        HttpPostedFile file = context.Request.Files[0];
                        //获得文件名
                        if (file.ContentLength > 0)
                        {
                            FileName = Path.GetFileName(file.FileName);
                        }
                        //string path = context.Request["getfiles"];//图片原始路径

                        //图片保存路径
                        string strPath = context.Request.MapPath("/Files/");
                        //判断是否存在路径，若无则创建该路径
                        if (!Directory.Exists(strPath))
                        {
                            Directory.CreateDirectory(strPath);
                        }

                        file.SaveAs(strPath + FileName);
                    }

                    Model.Police_FuzzTable emp = s.Find(x => x.AlarmId == id).FirstOrDefault();
                    emp.UserName = context.Request["getname"].ToString();
                    emp.UserSex = context.Request["Getsex"].ToString(); ;
                    emp.UserTel = context.Request["gettel"].ToString();
                    emp.UserEmail = context.Request["getemail"].ToString();
                    emp.UserAddress = context.Request["getcity"].ToString();
                    emp.UserPhoto = "/Files/" + FileName;
                    emp.LoginName = context.Request["getloginname"].ToString();
                    emp.LoginPwd = context.Request["getloginpwd"].ToString(); 
                    emp.UserIDCard = context.Request["getidcard"].ToString(); 
                    emp.RoleId = Convert.ToInt32(context.Request["getrole"]);
                    emp.OrganizeId = Convert.ToInt32(context.Request["getOrganize"]);
                    emp.DeptId = Convert.ToInt32(context.Request["getdept"]);
                    emp.FuzzUserStates = Convert.ToInt32(context.Request["getworkstate"]);
                    emp.FuzzDate = DateTime.Now.ToLocalTime();


                    var i = s.Update(emp);
                    string cc = "";
                        cc = "操作人警号:" + AmilyID.ToString();
                        cc += ",操作人：" + UserName.ToString() + "修改账户信息";
                        logger.Info(cc);
                    context.Response.Write(i); 
           
                }
                if (Actioon == EnumAction.Delete.ToString())
                {

                    var ids = Convert.ToInt32(context.Request["id"]);                  
                        var i = s.Delete(s.Find(x => x.AlarmId == ids).FirstOrDefault());
                        s.SaveChanges();
                        string cc = "";
                            cc = "操作人警号:" + AmilyID.ToString();
                            cc += ",操作人：" + UserName.ToString() + "删除账户信息";
                        logger.Info(cc);
                        context.Response.Write(i);

                }
            }
        

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}